package com.alphawavesgames.engine.graphics;

import android.graphics.Canvas;
import android.graphics.drawable.Drawable;

/**
 * A class that deals with animating images based on settings given.
 *
 * @author Andrew Dyer
 */
public class Animation {

    /** The collection of Drawables that will be shown in the order given. */
    private Drawable[] mImages;
    /** The time (in milliseconds) each image will be shown for. */
    private long[] mTimes;
    /** How far into the current image's display time we have endured. */
    private long mTimePassed;
    /** The index of the current image to be displayed. */
    private int mCurrentImage;
    /** The bounds of the drawable. */
    private int mLeftBound, mTopBound, mRightBound, mBottomBound;
    /** Tells if the animation loops or just runs through once. */
    private boolean mLoops = true;

    /** Creates a new Animation based on the given array of Drawables and their
     * accompanying durations.
     *
     * @param images An array of Drawables in drawing order.
     * @param times An array of times (in milliseconds) that accompany each
     * image to be drawn.
     */
    public Animation(Drawable[] images, long[] times) {
        mImages = images;
        mTimes = times;
        mTimePassed = 0;
    }

    /**
     * Updates the animation to show the correct image based on how much time
     * has passed since the last updated.
     *
     * @param elapsedTime How much time has passed since the last update;
     */
    public void update(long elapsedTime) {
        if (mImages.length > 1) { // if there is more than 1 image, animate.
            mTimePassed += elapsedTime;
            while (mTimePassed > mTimes[mCurrentImage]) {
                mTimePassed -= mTimes[mCurrentImage];
                mCurrentImage++;

                if (mCurrentImage >= mImages.length) {
                    if (mLoops) {
                        mCurrentImage -= mImages.length;
                    }
                    else {
                        mCurrentImage = mImages.length - 1;
                    }
                }
            }
        }
    }

    /**
     * Sets the drawing bounds of the Drawables.
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setBounds(int left, int top, int right, int bottom) {
        mLeftBound = left;
        mTopBound = top;
        mRightBound = right;
        mBottomBound = bottom;
    }

    /**
     * Draws the current image in the animation in the set bounds.
     *
     * @param c
     */
    public void draw(Canvas c) {
        if (mImages.length > 0) {
            mImages[mCurrentImage].setBounds(mLeftBound, mTopBound, mRightBound, mBottomBound);
            mImages[mCurrentImage].draw(c);
        }
    }
}
